<template>
  <a-drawer
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      :width="400"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
  >
    <a-form layout="vertical">
      <a-form-item label="费用类型" v-bind="validateInfos.cost_type">
        <a-cascader
            v-model:value="modelRef.cost_type"
            :options="costTypeList"
            :load-data="getCostTypeSub"
            placeholder="请选择费用类型"
        />
      </a-form-item>
      <a-form-item label="税收分类编码" v-bind="validateInfos.tax_code_id">
        <a-select
            v-model:value="modelRef.tax_code_id"
            placeholder="请选择税收分类编码"
            @change="handleTaxCodeChange"
        >
          <a-select-option
              v-for="item of taxCodeList"
              :key="item.id"
              :value="item.id"
          >{{ item.name }}
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <a-card class="tax-detail" size="small" v-if="modelRef.tax_code_id">
        <a-row :gutter="12" type="flex">
          <a-col flex="60px">
            <cu-icon type="org-tax" class="icon"></cu-icon
            >
          </a-col>
          <a-col flex="auto">
            <a-row class="fw-bold">{{ currentTaxCode.name }}</a-row>
            <a-row class="info">
              <a-col :span="4">税收分类编码</a-col>
              <a-col :span="20">{{ currentTaxCode.tax_code }}</a-col>
            </a-row>
            <a-row class="info">
              <a-col :span="4">税率</a-col>
              <a-col :span="20">{{ currentTaxCode.tax_rate }}%</a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-card>
      <a-form-item label="备注" v-bind="validateInfos.remark">
        <a-textarea
            v-model:value="modelRef.remark"
            placeholder="请输入备注"
            :rows="4"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, toRaw, toRefs, watch} from "vue";
import {Form, message} from "ant-design-vue";
import request from "../../../../common/utils/request";

const useForm = Form.useForm;

export default defineComponent({
  name: "AddTaxRate",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, {emit}) {
    const title = computed(() => {
      return props.id ? "编辑税率规则" : "新增税率规则";
    });

    const state = reactive({
      costTypeList: [],
      taxCodeList: [],
      currentTaxCode: {},
    });

    const handleTaxCodeChange = (value) => {
      state.currentTaxCode = state.taxCodeList.find((item) => item.id == value);
    };

    const onClose = () => {
      emit("cancel");
    };

    /**
     * @description: 表单
     */
    const modelRef = reactive({
      cost_type: undefined,
      tax_code_id: undefined,
      remark: "",
    });

    const required = [{required: true, message: "必填项"}];
    const rulesRef = reactive({
      cost_type: required,
      tax_code_id: required,
    });

    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate().then(() => {
        const params = {...toRaw(modelRef), needMsg: true};
        const success = (res) => {
          message.success(res.msg);
          emit("success");
        };
        if (params.cost_type && params.cost_type.length == 2) {
          params.cost_type = params.cost_type[1];
        } else {
          return;
        }
        if (props.id) {
          params.id = props.id;
          request
              .put("/org", "/invoice/taxRuleEdit", params)
              .then((res) => success(res));
        } else {
          request
              .post("/org", "/invoice/taxRuleAdd", params)
              .then((res) => success(res));
        }
      });
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request
          .get("/org", "/invoice/taxRuleInfo", {id: props.id})
          .then((res) => {
            const {detail} = res;
            if (detail.cost_type) {
              request
                  .get("/org", "/bill/getBillCostCategory", {
                    cost_type: detail.cost_type,
                  })
                  .then((res) => {
                    if (res.costData && res.costData.category_id) {
                      let category_id = res.costData.category_id;
                      request
                          .get("/org", "/bill/cost/categoryList", {is_bond: 0})
                          .then((result) => {
                            if (result.list) {
                              state.costTypeList = result.list.map((item1) => ({
                                label: item1.name,
                                value: item1.id,
                                isLeaf: false,
                              }));

                              state.costTypeList.forEach((item2) => {
                                if (item2.value == category_id) {
                                  request
                                      .get("/org", "/bill/costList", {
                                        page: 1,
                                        limit: 9999,
                                        category_id: category_id,
                                        status: 1,
                                        is_bond: 0,
                                      })
                                      .then((res) => {
                                        if (res.list) {
                                          item2.children = res.list.map((item) => ({
                                            label: item.name,
                                            value: item.cost_type,
                                            isLeaf: true,
                                          }));
                                          modelRef.cost_type = [
                                            category_id,
                                            detail.cost_type,
                                          ];
                                          setModelRef({
                                            tax_code_id:
                                                detail.tax_code_id || undefined,
                                            remark: detail.remark || "",
                                          });
                                          state.currentTaxCode = detail.tax_code_data;
                                        }
                                      });
                                }
                              });
                            }
                          });
                    }
                  });
            }
          });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      if (props.id) {
        getEditInfo();
      } else {
        getCostCategory();
      }
      request.get("/org", "/invoice/codeList").then((res) => {
        state.taxCodeList = res.list;
      });
    };

    const getCostCategory = () => {
      request.get("/org", "/bill/cost/categoryList", {is_bond: 0}).then((res) => {
        if (res.list) {
          state.costTypeList = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            // 打开时初始化数据
            init();
          } else {
            // 关闭时重置数据
            resetFields();
          }
        }
    );

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
            is_bond: 0,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              state.costTypeList = [...state.costTypeList];
            }
          });
    };

    return {
      title,
      modelRef,
      validateInfos,
      ...toRefs(state),
      resetFields,
      onSubmit,
      onClose,
      handleTaxCodeChange,
      getCostTypeSub,
    };
  },
});
</script>

<style lang="less" scoped>
.tax-detail {
  margin-top: -10px;
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;

  .icon {
    color: @primary-color;
    font-size: 30px;
  }

  .info {
    color: #999;
    font-size: 14px;
    margin-top: 8px;
  }
}
</style>
